# coding=utf-8
import commands
import os
from ShellUtils import shell_cmd


def handle_patch_file(base_git, patch_file, repo_name, dst_repo_nam):
    print("dst_repo_nam=%s" % dst_repo_nam)
    subject = ""

    diff_info = ""

    with open(patch_file) as f:
        f_lines = f.readlines()

        if os.path.exists(patch_file + "bk"):
            os.remove(patch_file + "bk")
        with open(patch_file + "bk", "w+") as fbk:
            base_git_split = base_git.strip().split("/")
            # git_last_dir_name = base_git_split[len(base_git_split) - 1]
            # print(git_last_dir_name)
            patch_file_split = os.path.abspath(os.path.join(patch_file, "..")).strip().split("/")

            for f_line in f_lines:

                if "Subject:" in f_line:
                    subject = f_line.strip()

                # create mode 100755 overlay/telephony/frameworks/base/core/res/res/values-mcc231-mnc01/config.xml
                if f_line.startswith(' create mode'):
                    temp_path = f_line.split(' ')[-1]
                    full_path = os.path.join(repo_name, temp_path)
                    ok_path = full_path[len(dst_repo_nam) + 1:]
                    write_line = f_line[:-len(temp_path)] + ok_path
                    print("create mode ok_path=%s write_line=%s" % (ok_path, write_line))
                    fbk.write(write_line)
                    diff_info = diff_info + write_line + "\n"
                # diff --git a/framesequence/jni/FrameSequence_webp.cpp b/framesequence/jni/FrameSequence_webp.cpp
                elif f_line.startswith("diff --git a/"):
                    ab_path = f_line[11:].split(" ")
                    a_path = ab_path[0].strip()
                    path = a_path[2:]

                    full_path = os.path.join(repo_name, path)
                    ok_path = full_path[len(dst_repo_nam) + 1:]
                    write_line = "diff --git a/" + ok_path + " " + "b/" + ok_path + os.linesep
                    print("create mode ok_path=%s write_line=%s" % (ok_path, write_line))
                    fbk.write(write_line)

                    diff_info = diff_info + write_line + "\n"

                    # result, fix_path = append_to_exist_path(base_git, patch_file_split, path)
                    # if result >= 0:
                    #     write_line = "diff --git a/" + fix_path + " " + "b/" + fix_path + os.linesep
                    #     fbk.write(write_line)
                    #     diff_info = diff_info + write_line + "\n"
                    # else:
                    #     fbk.close()
                    #     f.close()
                    #     return "", diff_info
                    # b_path = ab_path[1].strip()
                    # path = b_path[2:]
                    # ret, fix_b_path = append_to_exist_path(base_git, patch_file_split, path)
                    # if ret >= 0:
                    #     write_line = "diff --git a/" + fix_path + " " + "b/" + fix_path
                    #     fbk.write(write_line)
                    # else:
                    #     assert 2
                elif f_line.startswith("--- a/"):
                    path = f_line.strip()[6:]

                    full_path = os.path.join(repo_name, path)
                    ok_path = full_path[len(dst_repo_nam) + 1:]
                    write_line = "--- a/" + ok_path + os.linesep
                    fbk.write(write_line)
                    diff_info = diff_info + write_line + "\n"

                    # result, fix_path = append_to_exist_path(base_git, patch_file_split, path)
                    # if result >= 0:
                    #     write_line = "--- a/" + fix_path + os.linesep
                    #     fbk.write(write_line)
                    #     diff_info = diff_info + write_line + "\n"
                    # else:
                    #     fbk.close()
                    #     f.close()
                    #     return "", diff_info
                elif f_line.startswith("+++ b/"):
                    path = f_line.strip()[6:]

                    full_path = os.path.join(repo_name, path)
                    ok_path = full_path[len(dst_repo_nam) + 1:]
                    write_line = "+++ b/" + ok_path + os.linesep
                    fbk.write(write_line)
                    diff_info = diff_info + write_line + "\n"

                    # result, fix_path = append_to_exist_path(base_git, patch_file_split, path)
                    # if result >= 0:
                    #     write_line = "+++ b/" + fix_path + os.linesep
                    #     fbk.write(write_line)
                    #     diff_info = diff_info + write_line + "\n"
                    # else:
                    #     fbk.close()
                    #     f.close()
                    #     return "", diff_info
                else:
                    fbk.write(f_line)
            fbk.close()
        f.close()
    return subject, diff_info


def find_real_git_path(dst_code_path, repo_name):
    temp_git_path = dst_code_path + "/" + repo_name + "/"

    base_git_path = os.path.join(temp_git_path, ".git")
    if os.path.isdir(base_git_path):
        print("1find_real_git_path %s %s %s" % (dst_code_path, repo_name, temp_git_path))
        return temp_git_path[:-1]

    is_real_git = False
    while is_real_git is False:
        temp_git_path = os.path.abspath(os.path.join(temp_git_path, ".."))
        if len(dst_code_path) <= len(temp_git_path):
            if os.path.isdir(temp_git_path):
                base_git_path = os.path.join(temp_git_path, ".git")
                if os.path.isdir(base_git_path):
                    print("2find_real_git_path %s %s %s" % (dst_code_path, repo_name, temp_git_path))
                    return temp_git_path
        else:
            return None
    return None


def append_to_exist_path(base_git, patch_file_split, path):
    if os.path.isfile(os.path.join(base_git, path)):
        return 0, path
    temp_path = path
    for a_i in range(len(patch_file_split), 0, -1):
        # sub_dir = patch_file_split[i]
        for a_j in range(a_i - 1, 0, -1):
            temp_path = os.path.join(patch_file_split[a_j], temp_path)
            # print(temp_path)
            check_path = os.path.join(base_git, temp_path)
            # print(check_path)
            if os.path.isfile(check_path):
                return 1, temp_path
    print("append_to_exist_path error base_git=%s path=%s" % (base_git, path))
    return -1, path


def get_patch_from_code(code_path, git_path, commit_id, save_path):
    if code_path is None or len(code_path) <= 0:
        return -2, ""

    if git_path is None or len(code_path) <= 0:
        return -3, ""

    if commit_id is None or len(code_path) <= 0:
        return -4, ""

    if save_path is None or len(code_path) <= 0:
        return -5, ""

    aim_path = code_path + "/" + git_path
    if os.path.exists(save_path + "/" + git_path) is False:
        os.makedirs(save_path + "/" + git_path)
    patch_path = save_path + "/" + git_path
    cmd = "cd %s; git format-patch -1 %s -o %s" % (aim_path, commit_id, patch_path)
    print("get_patch_from_code execute_cmd %s" % cmd)
    # result = os.system(cmd)
    result, file_path = commands.getstatusoutput(cmd)
    if os.path.exists(file_path):
        if result != 0:
            os.remove(file_path)
        else:
            file_size = os.path.getsize(file_path)
            if file_size <= 0:
                result = -6
                os.remove(file_path)
    return result, file_path


def list_files(path):
    path_collection = []
    for dir_path, dir_names, file_names in os.walk(path):
        for _file in file_names:
            full_path = os.path.join(dir_path, _file)
            path_collection.append(full_path)
    return path_collection


def generate_path_use_diff(diff_dir, old, new, patch_path):
    cmd = "cd %s; diff -Naur %s %s > %s" % (diff_dir, old, new, patch_path)
    return shell_cmd(cmd)


def apply_patch_use_patch(dst_dir, patch_path, ignore_depth):
    cmd = "cd %s; patch --verbose -r - -l -Np%s -i %s" % (dst_dir, ignore_depth, patch_path)
    return shell_cmd(cmd)
